/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package ly.count.ohos.demo;

import ly.count.ohos.sdk.Countly;
import ly.count.ohos.sdk.RemoteConfigCallback;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ScrollView;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.configuration.Configuration;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Map;

/**
 * 远程配置示例页面
 *
 * @since 2021-04-13
 */
public class AbilityExampleRemoteConfig extends Ability {
    private static final String AA = "aa";
    private static final String DD = "dd";
    private static final String ERROR = "Error: ";
    private static final int TOAST_DIALOG_OFFSET_Y = 60;
    private static final int TOAST_DIALOG_TEXT_SIZE = 48;
    private static final int TOAST_DIALOG_TEXT_BACKGROUND_COLOR = 221;
    private static final int TOAST_DIALOG_TEXT_PADDING = 30;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_example_remote_config);
        findComponentById(ResourceTable.Id_button51).setClickedListener(this::onClickRemoteConfigUpdate);
        findComponentById(ResourceTable.Id_button47).setClickedListener(this::onClickRemoteConfigGetValue);
        findComponentById(ResourceTable.Id_button55).setClickedListener(this::onClickRemoteConfigGetValueInclusion);
        findComponentById(ResourceTable.Id_button56).setClickedListener(this::onClickRemoteConfigGetValueExclusion);
        findComponentById(ResourceTable.Id_button57).setClickedListener(this::onClickRemoteConfigClearValues);
        findComponentById(ResourceTable.Id_button58).setClickedListener(this::onClickRemoteConfigPrintValues);
        Countly.sharedInstance().onStart(this);

        ScrollView scrollView = (ScrollView) findComponentById(ResourceTable.Id_remote_config_scroll_view);
        scrollView.enableScrollBar(ScrollView.AXIS_Y, true);
    }

    private void onClickRemoteConfigUpdate(Component v) {
        Countly.sharedInstance().remoteConfig().update(new RemoteConfigCallback() {
            @Override
            public void callback(String error) {
                if (error == null) {
                    showToastDialog("Update finished");
                } else {
                    showToastDialog(ERROR + error);
                }
            }
        });
    }

    private void onClickRemoteConfigGetValue(Component v) {
        Object value = Countly.sharedInstance().remoteConfig().getValueForKey(AA);
        if (value != null) {
            showToastDialog("Stored Remote Config Value with key 'a': [" + value + "]");
        } else {
            showToastDialog("No value stored for this key");
        }
    }

    private void onClickRemoteConfigGetValueInclusion(Component v) {
        Countly.sharedInstance().remoteConfig().updateForKeysOnly(new String[]{AA, DD}, new RemoteConfigCallback() {
            @Override
            public void callback(String error) {
                if (error == null) {
                    showToastDialog("Update with inclusion finished");
                } else {
                    showToastDialog(ERROR + error);
                }
            }
        });
    }

    private void onClickRemoteConfigGetValueExclusion(Component v) {
        Countly.sharedInstance().remoteConfig().updateExceptKeys(new String[]{AA, DD}, new RemoteConfigCallback() {
            @Override
            public void callback(String error) {
                if (error == null) {
                    showToastDialog("Update with exclusion finished");
                } else {
                    showToastDialog(ERROR + error);
                }
            }
        });
    }

    private void onClickRemoteConfigClearValues(Component v) {
        Countly.sharedInstance().remoteConfig().clearStoredValues();
    }

    private void onClickRemoteConfigPrintValues(Component v) {
        // this sample assumes that there are 4 keys available on the server
        Map<String, Object> values = Countly.sharedInstance().remoteConfig().getAllValues();

        // access way #1
        Object value1 = null;
        Object value2 = null;
        Object value3 = null;
        Object value4;
        Object value5;

        if (values != null) {
            value1 = values.get(AA);
            value2 = values.get("bb");
            value3 = values.get("cc");
        }

        // access way #2
        value4 = Countly.sharedInstance().remoteConfig().getValueForKey(DD);
        value5 = Countly.sharedInstance().remoteConfig().getValueForKey("ee");

        String printValues = "";

        if (value1 != null) {
            // int value
            printValues = printValues + (int) value1;
        }

        final String or = "| ";
        if (value2 != null) {
            // float value
            printValues += or + (double) value2;
        }

        if (value3 != null) {
            // String value
            printValues += or + (String) value3;
        }

        if (value4 != null) {
            // array
            JSONArray jarray = (JSONArray) value4;
            printValues += or + jarray.toString();
        }

        if (value5 != null) {
            // json object
            JSONObject jobj = (JSONObject) value5;
            printValues += or + jobj.toString();
        }

        showToastDialog("Stored Remote Config Values: [" + printValues + "]");
    }

    @Override
    public void onStop() {
        Countly.sharedInstance().onStop();
        super.onStop();
    }

    @Override
    public void onConfigurationUpdated(Configuration newConfig) {
        super.onConfigurationUpdated(newConfig);
        Countly.sharedInstance().onConfigurationChanged(newConfig);
    }

    /**
     * 弹出ToastDialog
     *
     * @param textString
     */
    private void showToastDialog(String textString) {
        ToastDialog toastDialog = new ToastDialog(getContext().getApplicationContext());

        Component component = LayoutScatter.getInstance(getContext())
            .parse(ResourceTable.Layout_example_custom_text, null, false);
        Text text = (Text) component.findComponentById(ResourceTable.Id_text);
        text.setText(textString);

        toastDialog.setContentCustomComponent(component);
        toastDialog.show();
    }
}
